package com.hx78.org.demo2;

import com.google.api.core.ApiFuture;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class PublisherExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "mkp-dev-np1";
    String topicId = "test_by_linming";

    publisherExample(projectId, topicId);
  }

  public static void publisherExample(String projectId, String topicId)
      throws IOException, ExecutionException, InterruptedException {
    TopicName topicName = TopicName.of(projectId, topicId);

    Publisher publisher = null;
    try {
      // Create a publisher instance with default settings bound to the topic
      publisher = Publisher.newBuilder(topicName).build();

      String message = "Hello World 202";
      for (int i = 0; i < 50; i ++) {
        ByteString data = ByteString.copyFromUtf8(message + i);
//      PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
//      PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).setOrderingKey("1").build();
        PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).putAttributes("type", "filter2").build();

//      final Map<String, String> attrMap = new HashMap<>();
//      attrMap.put("type","catalogTaxonomyFilter");
//      publish(categoryChangeTopicId, new Gson().toJson(catalogTaxonomyFilter), attrMap);

        // Once published, returns a server-assigned message id (unique within the topic)
        ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
        String messageId = messageIdFuture.get();
        System.out.println("Published message ID: " + messageId);
      }

    } finally {
      if (publisher != null) {
        // When finished with the publisher, shutdown to free up resources.
        publisher.shutdown();
        publisher.awaitTermination(1, TimeUnit.MINUTES);
      }
    }
  }
}